package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.*;
import com.itheima.service.DeptService;
import com.itheima.service.EmpExprService;
import com.itheima.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;


@Service
public class EmpServiceImpl extends ServiceImpl<EmpMapper, Emp> implements EmpService {
    @Autowired
    private DeptService deptService;
    @Autowired
    private EmpExprService empExprSxervice;

    @Override
    public PageResult getPageResult(EmpQueryParam param) {
        //开启分页
        Page<Emp> objectPage = Page.of(param.getPage(), param.getPageSize());
        //根据最后修改时间倒序排序
        objectPage.addOrder(OrderItem.desc("update_time"));
        //条件分页查询
        //like 模糊查询名字 名字不为空 并且 不是空字符串
        objectPage = lambdaQuery().like(param.getName() != null && !param.getName().isEmpty(), Emp::getName, param.getName())
                .eq(param.getGender() != null, Emp::getGender, param.getGender())
                .between(param.getBegin() != null && param.getEnd() != null, Emp::getUpdateTime, param.getBegin(), param.getEnd())
                .page(objectPage);


        // 获取员工集合
        List<Emp> emps = objectPage.getRecords();
        // 获取部门id集合
        List<Integer> collect = emps.stream().map(emp -> {
            return emp.getDeptId();
        }).toList();
        if (!collect.isEmpty()) {
            // 根据部门id集合查询部门集合
            List<Dept> depts = deptService.listByIds(collect);

            emps.forEach(emp -> {
                depts.forEach(dept -> {
                    if (emp.getDeptId() != null && emp.getDeptId().equals(dept.getId())) {
                        emp.setDeptName(dept.getName());
                    }
                });
            });
        }

        //  返回结果
        return new PageResult(objectPage.getTotal(), emps);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveEmpExpr(Emp emp) {
        // 保存员工基本信息
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        save(emp);
        //保存员工工作经历信息
        List<EmpExpr> exprList = emp.getExprList();
        exprList.forEach(expr -> {
            expr.setEmpId(emp.getId());
        });
        empExprSxervice.saveBatch(exprList);
    }

    @Override
    public Emp getEmpById(Integer id) {
        Emp emp = getById(id);
        // 工作经历列表
        emp.setExprList(empExprSxervice.list(new LambdaQueryWrapper<EmpExpr>().eq(EmpExpr::getEmpId, id)));
        return emp;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateEmp(Emp emp) {
        emp.setUpdateTime(LocalDateTime.now());
        updateById(emp);

        //更新员工工作经历信息
        // 先删除
        empExprSxervice.remove(new LambdaQueryWrapper<EmpExpr>().eq(EmpExpr::getEmpId, emp.getId()));
        // 再保存
        List<EmpExpr> exprList = emp.getExprList();
        if (!exprList.isEmpty()) {
            exprList.forEach(expr -> {
                expr.setEmpId(emp.getId());
            });
            empExprSxervice.saveBatch(exprList);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeEmpsByIds(List<Integer> ids) {
        removeBatchByIds(ids);
        empExprSxervice.remove(new LambdaQueryWrapper<EmpExpr>().in(EmpExpr::getEmpId, ids));
    }
}
